package com.lanyun.dao.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lanyun.dao.base.TouruserBaseDao;
import com.lanyun.dao.intf.TouruserDao;
import com.lanyun.entity.TouruserEntity;
import com.lanyun.mapper.TouruserMapper;
import com.lanyun.util.HttpClientUtil;
import com.lanyun.util.Secretity;
import com.lanyun.wrapper.TouruserQuery;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * TouruserDaoImpl: 数据操作接口实现
 *
 * 这只是一个减少手工创建的模板文件
 * 可以任意添加方法和实现, 更改作者和重定义类名
 * <p/>@author Powered By Fluent Mybatis
 */
@Repository
public class TouruserDaoImpl extends TouruserBaseDao implements TouruserDao {
    @Resource
    TouruserMapper touruserMapper;
    @Override
    public Boolean login(String info) {
        JSONObject jsonObject = JSONUtil.parseObj(info);
        TouruserEntity userInfo = JSONUtil.toBean(jsonObject.get("userInfo").toString(),TouruserEntity.class);
        String code = (String)jsonObject.get("code");
        //1、非空校验
        //校验code
        if(Secretity.IsNull(info)){
            return false;
        }
        //2、调用微信的登录接口，模拟http请求
        String httpUrl = "https://api.weixin.qq.com/sns/jscode2session?appid="+Secretity.APPID+
                "&secret="+Secretity.AppSecret+"&js_code="+code+"&grant_type=authorization_code";
        String result = HttpClientUtil.doGet(httpUrl);
        System.out.println("result = "+result);

        //3、把字符串转化成json对象
        JSONObject jsonObject1 = JSONUtil.parseObj(result);
        String session_key = jsonObject1.get("session_key").toString();
        //拿到openid
        String openid = jsonObject1.get("openid").toString();
        //4、去查询openid是否在数据库中
        TouruserEntity one = touruserMapper.findOne(new TouruserQuery().where.openId().eq(openid).end());
        //5、在就返回true，不在就insert，返回true
        if (StringUtils.isEmpty(one)){
            userInfo.setOpenId(openid);
            userInfo.setSessionKey(session_key);
            touruserMapper.save(userInfo);
        }
        return true;
    }
}
